/*
 * The MIT License
 *
 * Copyright (c) 2013-2016 reark project contributors
 *
 * https://github.com/reark/reark/graphs/contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package io.reark.rxgithubapp.advanced.slice;


import com.google.gson.Gson;
import io.reark.reark.utils.Log;
import io.reark.rxgithubapp.ResourceTable;
import io.reark.rxgithubapp.advanced.ability.MainAbility;
import io.reark.rxgithubapp.advanced.data.*;
import io.reark.rxgithubapp.advanced.widget.WidgetService;
import io.reark.rxgithubapp.shared.view.RepositoriesAdapter;
import io.reark.rxgithubapp.shared.network.NetworkApi;
import io.reark.rxgithubapp.shared.pojo.GitHubRepository;
import io.reark.rxgithubapp.shared.pojo.GitHubRepositorySearchResults;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import static ohos.agp.components.Component.FOCUS_ENABLE;

public class RepositoriesSlice extends AbilitySlice {

    private RepositoriesAdapter repositoriesAdapter;
    private Text text;
    private GitHubRepositoryList gitHubRepositoryList;
    private DatabaseHelper helper = new DatabaseHelper(this);
    private OrmContext connect;
    List<GitHubRepository> gitHubRepositories = new ArrayList<>();
    private String string = "";

    @Override
    protected void onStart(Intent intent) {
        System.out.println("--------onStart----->>>");
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_repositories);
        connect = helper.getOrmContext(DbUtils.A_LIAS, DbUtils.DB, GithubDb.class);
        gitHubRepositories = new ArrayList<>();
        ListContainer repositoriesListView = (ListContainer) findComponentById(ResourceTable.Id_repositories_list_view);
        TextField textField = (TextField) findComponentById(ResourceTable.Id_repositories_search);
        textField.requestFocus();
        EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
        textField.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String text, int start, int before, int count) {
                if (text.length() > 2) {
                    handler.removeAllEvent();
                    handler.postTask(new Runnable() {
                        @Override
                        public void run() {
                            getData(text);
                        }
                    }, 500);
                } else {
                    handler.removeAllEvent();
                }


            }
        });
        text = (Text) findComponentById(ResourceTable.Id_repositories_status_text);
        textField.setText("");
        text.setText(" ");
        repositoriesAdapter = new RepositoriesAdapter(gitHubRepositories, this);
        repositoriesListView.setItemProvider(repositoriesAdapter);

        repositoriesListView.setItemClickedListener((listContainer, component, i, l) -> {

            Intent intent1 = new Intent();
            GitHubRepository gitHubRepository=gitHubRepositories.get(i);
            UserSettings userSettings=new UserSettings();
            userSettings.setAvatarUrl(gitHubRepository.getOwner().getAvatarUrl());
            userSettings.setName(gitHubRepository.getName());
            userSettings.setForksCount(gitHubRepository.getForksCount());
            userSettings.setStargazersCount(gitHubRepository.getStargazersCount());
            userSettings.setId((long) gitHubRepository.getId());
            DbUtils.setWidget(userSettings,this);
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName(getBundleName())
                    .withAbilityName(MainAbility.class.getName())
                    .build();
            intent1.setOperation(operation);
            startAbility(intent1);
        });
        getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                try {
                    showSoftInput();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },500);
    }

    private void showSoftInput() throws Exception {
        Class inputClass = Class.forName("ohos.miscservices.inputmethod.InputMethodController");
        Method method = inputClass.getMethod("getInstance");
        Object object = method.invoke(new Object[]{});
        Method startInput  = inputClass.getMethod("startInput",int.class,boolean.class);
        startInput.invoke(object, 1, true);
    }

    private void getData(String str) {

        if (str.length() < 3) {
            return;
        }
        text.setText("Loading..");
        List<FormJson> json = DbUtils.query(str, connect);

        if (json.size() > 0) {
            if (!NetworkApi.isNetworkConnectedInternet(this)) {
                text.setText("Error occurred");
            }
            String formJson = json.get(0).getJson();
            GitHubRepositoryList fromJson = new Gson().fromJson(formJson, GitHubRepositoryList.class);
            gitHubRepositories = fromJson.getList();
            repositoriesAdapter.set(gitHubRepositories);

            return;
        }

        if (!NetworkApi.isNetworkConnectedInternet(this)) {
            text.setText("Error occurred");
            return;
        }
        String baseUrl = "";
        try {
            baseUrl =  getResourceManager().getElement(io.reark.rxgithubapp.shared.ResourceTable.String_base_url).getString();
        } catch (IOException | NotExistException | WrongTypeException e) {
            Log.d("tag",e.getMessage());
        }
        Call<GitHubRepositorySearchResults> dataCall = new NetworkApi(baseUrl).search(str);
        dataCall.enqueue(new Callback<GitHubRepositorySearchResults>() {
            @Override
            public void onResponse(Call<GitHubRepositorySearchResults> call, Response<GitHubRepositorySearchResults> response) {

                if (response.body() != null) {
                    text.setText(" ");
                    List<GitHubRepository> list = response.body().getItems();
                    gitHubRepositoryList = new GitHubRepositoryList();
                    if (list.size() > 5) {
                        gitHubRepositories = list.subList(0, 5);
                    } else {
                        gitHubRepositories = response.body().getItems();
                    }
                    if (list.size() == 0){
                        return;
                    }
                    repositoriesAdapter.set(gitHubRepositories);
                    gitHubRepositoryList.setList(gitHubRepositories);

                    String json = new Gson().toJson(gitHubRepositoryList);
                    if (string.equals(json)) {
                        return;
                    }
                    string = json;
                    FormJson formJson = new FormJson();
                    formJson.setName(str);
                    formJson.setJson(json);
                    DbUtils.insertJson(str, formJson, connect);

                } else {
                    text.setText("Error occurred");
                }

            }

            @Override
            public void onFailure(Call<GitHubRepositorySearchResults> call, Throwable throwable) {

            }
        });
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

}

